import { Button, message } from "antd";
import request from "../../axios/request";
import { useEffect, useRef } from "react";

function Index() {
  const [messageApi, contextHolder] = message.useMessage();
  const price = "《红楼梦》";
  const subject = 300;
  const timer = useRef(null);
  useEffect(() => {
    return () => {
      if (timer.current) clearInterval(timer.current);
    };
  }, []);
  const dianji = async () => {
    await request
      .post("/order/create", {
        price: price,
        subject: subject,
      })
      .then((res) => {
        if (res.data.code == 200) {
          messageApi.info(res.data.msg);
          const obj = res.data.data;
          zhifu(obj);
        }
      });
  };

  const zhifu = async (obj: { orderId: any; subject: any; }) => {
    await request
      .post("/order/alipay", {
        orderNo: obj.orderId,
        totalPrice: obj.subject,
        subject: "适合大学生看的书",
      })
      .then((res) => {
        console.log(res);
        if (res.data.code == 200) {
          window.open(res.data.url);
          zhifujieguo(obj.orderId);
        }
      });
  };
  const zhifujieguo = (id: any) => {
    timer.current = setInterval(async () => {
      const res = await request.post("/order/getPayStatus", {
        out_trade_no: id,
      });
      if (res.data.data.tradeStatus == "TRADE_SUCCESS") {
        clearInterval(timer.current);
        messageApi.open({
          type: "success",
          content: "恭喜您，支付成功！",
          duration: 10,
        });
      }
    }, 10000);
  };
  return (
    <div>
      <div>
        {contextHolder}
        <h1>{price}</h1>
        <h3>{subject}</h3>
        <Button onClick={dianji}>创造订单</Button>
      </div>
    </div>
  );
}

export default Index;
